#include "history.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define HISTORY_FILE ".history.txt"

int saveHistory(listHistory l) {
	FILE *hist = fopen(HISTORY_FILE,"w+");
	nodeHistory node = l->head;

	if(hist == NULL)
		return 0;

	while(node != NULL) {
		fprintf(hist,"%d %s\n",(int)strlen(node->string),node->string);
		node = node->next;
	}

	fclose(hist);
	return 1;

}

listHistory loadHistory(void) {
	listHistory l = createListHistory();
	FILE *hist = fopen(HISTORY_FILE,"r");
	int continua=1;

	if(l == NULL)
		return NULL;

	while(continua) {
		int size;
		char *string;

		fscanf(hist,"%d",&size);
		string = (char *)malloc((size+1)*sizeof(char));		
		continua = (fscanf(hist,"%s\n",string) == 1);
		if(continua)
			insertNodeHistory(l,string);
	}


	fclose(hist);
	return l;

}

listHistory createListHistory(void) {
	listHistory l;

	l = (listHistory)malloc(sizeof(struct _LINKED_LIST_HISTORY));
	if(l == NULL) {
		return NULL;
	} else {
		l->size = 0;
		l->head = NULL;

		return l;
	}
}

int prependNodeHistory(listHistory l, char *string) {
	nodeHistory n;
	nodeHistory new_node;


	n = l->head;

	new_node = (nodeHistory)malloc(sizeof(struct _NODE_HISTORY));
	new_node->string = (char *)malloc((1+strlen(string))*sizeof(char));
	strcpy(new_node->string,string);
	new_node->next = NULL;
	new_node->prev = NULL;
	
	if(new_node == NULL) {
		return 0;
	}

	if(n == NULL) {
		l->head = new_node;	

		new_node->next = NULL;
		new_node->prev = NULL;

		(l->size)++;
		return 1;
	} else {
		if(strcmp(l->head->string,string) == 0) {
			return 0;
		}
		new_node->next = n;
		new_node->prev = NULL;

		n->prev = new_node;
		
		l->head = new_node;

		(l->size)++;

		return 1;
	}	

}

int insertNodeHistory(listHistory l, char *string) {
	nodeHistory n;
	nodeHistory new_node;

	n = l->head;

	new_node = (nodeHistory)malloc(sizeof(struct _NODE_HISTORY));
	new_node->string = (char *)malloc((1+strlen(string))*sizeof(char));
	strcpy(new_node->string,string);
	new_node->next = NULL;
	new_node->prev = NULL;
	
	if(new_node == NULL) {
		return 0;
	}

	if(n == NULL) {
		l->head = new_node;	
		(l->size)++;
		return 1;
	} else {
		while(n->next != NULL) {
			n = n->next;
		}

		new_node->prev = n;
		n->next = new_node;
		(l->size)++;
		return 1;
	}	
}

void printHistory(listHistory l) {
	nodeHistory node = l->head;
 	int i=1;

	printf("------------------------\n\r");
	printf("Terminal Command History\n\r");
	printf("------------------------\n\r\n\r");
	while(node != NULL) {
		printf(" %d. %s\n\r",i++,node->string);
		node = node->next;
	}
	printf("\n\r");
}
